package cn.edu.zut.salarymanagesystem.fragments;

import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.text.SimpleDateFormat;

import cn.edu.zut.salarymanagesystem.R;
import cn.edu.zut.salarymanagesystem.bean.vo.Notice;
import cn.edu.zut.salarymanagesystem.bean.vo.WorksVO;
import cn.edu.zut.salarymanagesystem.config.Storage;
import cn.edu.zut.salarymanagesystem.utils.AlertBuilder;
import cn.edu.zut.salarymanagesystem.utils.Browser;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainFragment extends Fragment {
    Button btnComin;
    TextView txtSalary;
    TextView txtUid;
    // 将时间戳转换成日期时间格式
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    TextView txtGroup;

    TextView notice;
    private static final byte SET_NOTIFY = 0x01;
    private static final byte REND_INFO = 0x02;
    private static final byte NET_ERROR = 0x03;
    private static final byte COMIN_SUCCESS = 0x04;
    private static final byte COMIN_ALREADY = 0x05;
    private static final byte COMIN_ERROR = 0x06;
    private static final byte COMIN_CHECK_ERROR = 0x07;
    private static final byte COMIN_HALF = 0x08;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SET_NOTIFY:
                    notice.setText((String) msg.obj);
                    break;
                case REND_INFO:
                    WorksVO worksVO = (WorksVO) msg.obj;
                    txtSalary.setText(worksVO.getTotal() + "元");
                    txtGroup.setText(Storage.currentUser.getGroupName());
                    txtUid.setText(String.valueOf(Storage.currentUser.getUid()));
                    break;
                case NET_ERROR:
                    Toast.makeText(getActivity(), "请求失败！请检查网络设置", Toast.LENGTH_SHORT).show();
                    break;
                case COMIN_SUCCESS:
                    btnComin.setText("已签到");
                    btnComin.setEnabled(false);
                    Toast.makeText(getActivity(), "签到成功", Toast.LENGTH_SHORT).show();
                    break;
                case COMIN_ALREADY:
                    btnComin.setEnabled(false);
                    btnComin.setText("已签到");
                    break;
                case COMIN_ERROR:
                    Toast.makeText(getActivity(), "签到失败", Toast.LENGTH_SHORT).show();
                    break;
                case COMIN_CHECK_ERROR:
                    Toast.makeText(getActivity(), "签到状态检查失败！", Toast.LENGTH_SHORT).show();
                    break;
                case COMIN_HALF:
                    btnComin.setText("半天到");
                    btnComin.setEnabled(false);
                    break;
            }
        }
    };

    public MainFragment() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        //获取公告信息：
        notice = view.findViewById(R.id.main_gonggao);
        showNotice();
        //绑定UI控件：
        txtSalary = view.findViewById(R.id.txt_value);
        txtUid = view.findViewById(R.id.txt_uid);
        txtGroup = view.findViewById(R.id.txt_group);
        //为签到设置点击监听
        btnComin = view.findViewById(R.id.btn_comin);
        btnComin.setOnClickListener(this.cominListener);
        //TODO: 实现半天假期和加班时长功能
        btnComin.setOnLongClickListener(cominLongListener);
        initUI();
        return view;
    }


    private void showNotice() {
        Request request = new Request.Builder().url(Storage.url + "/notice/getNew").build();
        Browser.getClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e("d8g", "获取公告失败！");
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String string = response.body().string();
                Message msg = Message.obtain();
                Notice notice = JSON.parseObject(string, Notice.class);
                String content = "公告获取失败";
                if (notice != null)
                    content = notice.getContent();
                msg.what = SET_NOTIFY;
                msg.obj = "\t" + content;
                handler.sendMessage(msg);
            }
        });
    }

    public void initUI() {
        Request request = new Request.Builder().url(Storage.url + "/workRecord/selectAll").build();
        //渲染用户的工资等数据
        new Thread(() -> {
            try {
                Response execute = Browser.getClient().newCall(request).execute();
                String json = execute.body().string();
                WorksVO vo = JSON.parseObject(json, WorksVO.class);
                Message obtain = Message.obtain();
                obtain.what = REND_INFO;
                obtain.obj = vo;
                handler.sendMessage(obtain);
            } catch (IOException e) {
                Log.e("d8g", "MainFragement::initUI: " + e.getMessage());
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }).start();
        //计算签到按钮样式
        Request cominRequest = new Request.Builder().url(Storage.url + "/attendance/isDone").build();
        Browser.getClient().newCall(cominRequest).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                handler.sendEmptyMessage(COMIN_CHECK_ERROR);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String result = response.body().string();
                switch (result) {
                    case "ALL":
                        handler.sendEmptyMessage(COMIN_ALREADY);
                        break;
                    case "HALF":
                        handler.sendEmptyMessage(COMIN_HALF);
                        break;
                    case "NOT":
                        //那就什么都不做
                        break;
                }
            }
        });
    }

    private View.OnClickListener cominListener = v -> {
        OkHttpClient httpClient = Browser.getClient();
        Request request = new Request.Builder().url(Storage.url + "/attendance/comin").build();
        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                handler.sendEmptyMessage(COMIN_ERROR);
                Log.e("d8g", "Comin onFailure: " + e.getMessage());
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                //response.body().string()只能調用一次
                String result = response.body().string();
                if (result.equals("SUCCESS")) {
                    handler.sendEmptyMessage(COMIN_SUCCESS);
                    return;
                } else if (result.equals("ALREADY")) {
                    handler.sendEmptyMessage(COMIN_ALREADY);
                }
                handler.sendEmptyMessage(COMIN_ERROR);
            }
        });
    };
    private View.OnLongClickListener cominLongListener = view -> {
        AlertDialog dialog = AlertBuilder.getAttendanceDialog(MainFragment.this.getActivity(),handler);
        dialog.show();
        return false;
    };

}
/**
 * 这里我遇到一个BUG，这里我记录一下：
 * 我是用client作为一个属性，在注销之后重新登录，就回导致client为原来的client,
 * 也就是原来的client的cookie被保留了下来，所以这里我需要使用新的client来发送请求，
 * 因为这个 Fragment 的生命周期是整个应用程序的，所以这里的client也是原来账号下对应的client
 * 其他的地方使用的都是：SingleHttpClient.getClient()这种用法，而错误的写法是：client
 * 在注销之后我进行了：SingleHttpClient.getInstance().flushClient();进而执行了：client = null;
 * 所以导致了某些异常情况
 */